//
// Created by Administrator on 2024/4/8.
// arr to linkedlist
//https://blog.csdn.net/qq_45836906/article/details/105712032


#include <iostream>
#include <vector>

using namespace std;

struct Node
{
    int v;
    Node *next;
};

vector<int> l = {1, 2, 3, 4, 5, 6};

void test_new()
{
    for (int i = 0; i < 5; ++i)
    {
        Node t{1, nullptr};
        // 变量在栈内存中, 生命周期结束后, 栈指针会回到当初的位置
        // 每次循环,t的地址都是一样的
        cout << i << ' ' << &t << endl;
        // 变量在堆内存中, 如果没有用delete, 变量一直存在
        Node *p = new Node();
        cout << i << ' ' << p << endl;
//        delete p;
    }

}

void build01()
{
    Node *head = new Node();
    Node *cur = head;
    for (int i = 0; i < l.size(); ++i)
    {
        cur->v = l[i];
        if (i == l.size() - 1)
        {
            cur->next = nullptr;
            break;
        }
        cur->next = new Node();
        cur = cur->next;
    }
    // print linked list
    cur = head;
    while (cur != nullptr)
    {
        cout << cur->v << endl;
        cur = cur->next;
    }
}

void build02()
{
    Node *head = new Node();
    Node *cur = head;
    for (int i = 0; i < l.size(); ++i)
    {
        // 这样的话,指向是不变的
        Node t{l[i], nullptr};
//        cur->next=&t;
        cur = &t;
        cur = cur->next;
//        cur->next=nullptr;
    }
    cur = head;
    while (cur->next != nullptr)
    {
        cout << cur->v << endl;
        cur = cur->next;
    }
}

void build03()
{
    Node *head = new Node;
    Node *cur = head;
    for (int i = 0; i < l.size(); ++i)
    {
        Node *t = new Node;
        t->v = l[i];
        t->next = nullptr;
        cur->next = t;
        cur = cur->next;
    }
    cur = head->next;
    while (cur != nullptr)
    {
        cout << cur->v << endl;
        cur = cur->next;
    }
}

void build04()
{
    Node *head = new Node();
    Node *cur = head;
    for (int i = 0; i < l.size(); ++i)
    {
//        cur->next=new Node{l[i], nullptr};
        cur->next = new Node();
        cur->next->v = l[i];
        cur = cur->next;
    }
    cur = head->next;
    while (cur != nullptr)
    {
        cout << cur->v << endl;
        cur = cur->next;
    }
}

// 建立链表 头插法 倒序输出
void buildL()
{
    Node *head = new Node();
    Node *cur = head->next;
    for (int i = 0; i < l.size(); ++i)
    {
        Node *t = new Node{l[i], nullptr};
        head->next = t;
        t->next = cur;
        cur = head->next;
    }
    while(cur!=nullptr)
    {
        cout<<cur->v<<' ';
        cur=cur->next;
    }
}

int main()
{
//    test_new();
// build函数用尾插法 输出是正序
//    build01();
//    build02();
//    build03();
//    build04();
    // buildL 用头插法 输出是倒序
    buildL();
    return 0;
}